package com.duowei.diandan.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.duowei.diandan.BuildConfig;
import com.duowei.diandan.R;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.UserCardInfo;
import com.duowei.diandan.constant.CloudLoginFavorite;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.constant.SqlStr;
import com.duowei.diandan.databinding.CloudLoginFragmentBinding;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.entry.Wxfwqdz;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.Post6Listener;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.zl.reik.dilatingdotsprogressbar.DilatingDotsProgressBar;

import java.util.List;

public class CloudLoginFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = "CloudLoginFragment";

    private CloudLoginFragmentBinding mBinding;

    private DilatingDotsProgressBar mProgressBar;

    private TextView.OnEditorActionListener mOnEditorActionListener = (v, actionId, event) -> {
//        Log.d(TAG, "v: " + v);
//        Log.d(TAG, "actionId: " + actionId);
//        Log.d(TAG, "event: " + event);

        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            scanInput(v);
            mBinding.scanEditText.setText(null);
            return true;
        } else {
            return false;
        }
    };

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d(TAG, "beforeTextChanged: s = " + s);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d(TAG, "onTextChanged: s = " + s);
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "afterTextChanged: s = " + s);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cloud_login, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (CloudLoginFavorite.ONLY_INPUT == Settings.CLOUD_LOGIN_FAVORITE) {
            mBinding.inputCardView.setVisibility(View.VISIBLE);
            mBinding.scanCardView.setVisibility(View.INVISIBLE);
            mBinding.inputButton.setVisibility(View.INVISIBLE);

        } else if (CloudLoginFavorite.ONLY_SCAN == Settings.CLOUD_LOGIN_FAVORITE) {
            mBinding.scanCardView.setVisibility(View.VISIBLE);
            mBinding.inputCardView.setVisibility(View.INVISIBLE);
            mBinding.scanButton.setVisibility(View.INVISIBLE);

            mBinding.scanEditText.setOnEditorActionListener(mOnEditorActionListener);

        } else {
            if (CloudLoginFavorite.SCAN_LOGIN == Settings.CLOUD_LOGIN_FAVORITE) {
                mBinding.inputCardView.setRotationY(-90);
                mBinding.inputCardView.setVisibility(View.INVISIBLE);
            } else {
                mBinding.scanCardView.setRotationY(-90);
                mBinding.scanCardView.setVisibility(View.INVISIBLE);
            }

            mBinding.inputButton.setOnClickListener(v -> flipCardView());
            mBinding.scanButton.setOnClickListener(v -> flipCardView());

            mBinding.scanEditText.setOnEditorActionListener(mOnEditorActionListener);
        }

        mBinding.num0.setOnClickListener(this);
        mBinding.num1.setOnClickListener(this);
        mBinding.num2.setOnClickListener(this);
        mBinding.num3.setOnClickListener(this);
        mBinding.num4.setOnClickListener(this);
        mBinding.num5.setOnClickListener(this);
        mBinding.num6.setOnClickListener(this);
        mBinding.num7.setOnClickListener(this);
        mBinding.num8.setOnClickListener(this);
        mBinding.num9.setOnClickListener(this);
        mBinding.numDelete.setOnClickListener(this);

        mBinding.loginButton.setOnClickListener(v -> {
            cloudLogin(mBinding.cardNoView.getText().toString(),
                    mBinding.cardPasswdView.getText().toString());
        });

        mBinding.backButton.setOnClickListener(v -> {
            if (mOnClickListener != null) {
                mOnClickListener.onBackClick();
            }
        });

        setQrCodeImage();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        super.onResume();
        if (BuildConfig.DEBUG) {
            mBinding.cardNoView.setText("15260202690");
            mBinding.cardPasswdView.setText("123456");
        } else {
            mBinding.cardNoView.setText(null);
            mBinding.cardPasswdView.setText(null);
        }
    }

    private EditText getFocusedEditText() {
        EditText et1 = mBinding.cardNoView;
        EditText et2 = mBinding.cardPasswdView;

        if (et1.isFocused()) {
            return et1;
        } else if (et2.isFocused()) {
            return et2;
        } else {
            et1.requestFocus();
            return et1;
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        EditText editText = getFocusedEditText();

        int id = v.getId();
        switch (id) {
            case R.id.num0:
            case R.id.num1:
            case R.id.num2:
            case R.id.num3:
            case R.id.num4:
            case R.id.num5:
            case R.id.num6:
            case R.id.num7:
            case R.id.num8:
            case R.id.num9:
                if (editText != null) {
                    editText.setText(editText.getText().toString() + ((TextView) v).getText().toString());
                }
                break;
            case R.id.numDelete:
                if (editText != null) {
                    int len = editText.getText().length();
                    if (len > 0) {
                        editText.setText(editText.getText().subSequence(0, len - 1));
                    }
                }
                break;
        }
    }

    /**
     * 扫描输入
     *
     * @param view
     */
    private void scanInput(TextView view) {
        String input = view.getText().toString();

        if (input.contains(",")) {
            String[] items = input.split(",");

            // --
            if (items[0].length() % 2 == 0) {
                int length = items[0].length();
                String i1 = items[0].substring(0, length / 2);
                String i2 = items[0].substring(length / 2, length);

                if (i1.equals(i2)) {
                    items[0] = i1;
                }
            }
            if (items.length >= 2) {
                if (items[1].length() % 2 == 0) {
                    int length = items[1].length();
                    String i1 = items[1].substring(0, length / 2);
                    String i2 = items[1].substring(length / 2, length);

                    if (i1.equals(i2)) {
                        items[1] = i1;
                    }
                }
            }

            // --
            if (items.length == 1) {
                cloudLogin(items[0].replaceAll("\\s+", ""), "");

            } else if (items.length >= 2) {
                cloudLogin(items[0].replaceAll("\\s+", ""),
                        items[1].replaceAll("\\s+", ""));
            }
        }
    }

    public void setLanding(boolean landing) {
        if (landing) {
            mBinding.mainLayout.setVisibility(View.INVISIBLE);
            mBinding.dotsProgressLayout.setVisibility(View.VISIBLE);
            mBinding.dotsProgressBarLayout.removeAllViews();

            mProgressBar = new DilatingDotsProgressBar(getContext());
            mProgressBar.setDotColor(Color.WHITE);
            mProgressBar.setNumberOfDots(6);
            mProgressBar.setDotSpacing(20);
            mProgressBar.setDotScaleMultpiplier(3);
            mProgressBar.setGrowthSpeed(1000);

            mBinding.dotsProgressBarLayout.addView(mProgressBar);
            mProgressBar.showNow();

        } else {
            mBinding.mainLayout.setVisibility(View.VISIBLE);
            mBinding.dotsProgressLayout.setVisibility(View.GONE);
            if (mProgressBar != null) {
                mProgressBar.hide();
            }
        }
    }

    /**
     * 云会员登录
     */
    private void cloudLogin(String cardCode, final String cardPassword) {
        if (mOnClickListener != null) {
            mOnClickListener.onLoginClick();
        }

        if (TextUtils.isEmpty(cardCode)) {
            sendMessage("请输入卡号");
        } else {
            Wxfwqdz wxfwqdz = AppDatabase.getDatabase().wxfwqdzDao().findOne();
            if (wxfwqdz != null) {
                NetUtils.post6(NetConfig.getWeiXinServerUrl(wxfwqdz.getAndroidSip()),
                        SqlStr.getMemberUserCardInfo(cardCode, cardCode, String.valueOf(wxfwqdz.getWeid())),
                        UserCardInfo.class, new Post6Listener<UserCardInfo>() {
                            @Override
                            public void onFail(Exception e) {
                                sendMessage("网络错误");
                            }

                            @Override
                            public void onSuccess(List<UserCardInfo> list) {
                                if (list == null || list.size() == 0) {
                                    sendMessage("没有符合查询条件的会员\n电话号码或消费密码错误");
                                } else {
                                    UserCardInfo uci = list.get(0);
                                    OrderList.getInstance().setUserCardInfo(uci);

                                    if (uci.getOccupation() == null) {
                                        uci.setOccupation("");
                                    }

                                    if (cardPassword.equals(uci.getOccupation())) {
                                        if ("0".equals(uci.getStatus())) {
                                            // 停用
                                            sendMessage("该会员已停用\n您不能进行消费");

                                        } else {
                                            if (mOnClickListener != null) {
                                                if (OrderMode.SELF_SERVICE_MEMBER == Settings.ORDER_MODE) {
                                                    OrderList.getInstance().computeCurrentMemberGrade();
                                                    mOnClickListener.onMemberModeClick(uci);

                                                } else {
                                                    // ok, 进入详情界面
                                                    mOnClickListener.onLoginSuccess(uci);
                                                }
                                            }
                                        }
                                    } else {
                                        sendMessage("没有符合查询条件的会员\n电话号码或消费密码错误");
                                    }
                                }
                            }
                        });
            } else {
                sendMessage("未发现微信服务器设置");
            }
        }
    }

    private void sendMessage(String message) {
        if (mOnClickListener != null) {
            mOnClickListener.onLoginMessage(message);
        }
    }

    private void setQrCodeImage() {
        Wxfwqdz wxfwqdz = getDb().wxfwqdzDao().findOne();
        if (wxfwqdz != null
                && !TextUtils.isEmpty(wxfwqdz.getSip())
                && !TextUtils.isEmpty(wxfwqdz.getWeid())) {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            try {
                String url = String.format("http://%s/mobile.php?act=entry&eid=7&weid=%s", wxfwqdz.getSip(), wxfwqdz.getWeid());
                DisplayMetrics metrics = new DisplayMetrics();
                //noinspection ConstantConditions
                getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int width = metrics.widthPixels / 3;
                Bitmap bitmap = barcodeEncoder.encodeBitmap(url, BarcodeFormat.QR_CODE, width, width);
                mBinding.cloudLoginQrCodeView.setImageBitmap(bitmap);
            } catch (WriterException e) {
                Log.e(TAG, "setQrCodeImage: ", e);
            }

        } else {
            Toast.makeText(getContext(), "微信服务器信息不完整,不能生成二维码", Toast.LENGTH_SHORT).show();
        }
    }

    // --

    private OnClickListener mOnClickListener;

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    public interface OnClickListener {
        void onBackClick();

        void onLoginClick();

        void onLoginMessage(String message);

        void onLoginSuccess(UserCardInfo userCardInfo);

        void onMemberModeClick(UserCardInfo userCardInfo);
    }

    private Interpolator mAccelerator = new AccelerateInterpolator();
    private Interpolator mDecelerator = new DecelerateInterpolator();

    private void flipCardView() {
        final ViewGroup visibleCardView;
        final ViewGroup invisibleCardView;

        if (mBinding.inputCardView.getVisibility() == View.INVISIBLE) {
            visibleCardView = mBinding.scanCardView;
            invisibleCardView = mBinding.inputCardView;
        } else {
            invisibleCardView = mBinding.scanCardView;
            visibleCardView = mBinding.inputCardView;
        }

        ObjectAnimator visToInvis = ObjectAnimator.ofFloat(visibleCardView, "rotationY", 0, 90);
        visToInvis.setDuration(500);
        visToInvis.setInterpolator(mAccelerator);

        ObjectAnimator invisToVis = ObjectAnimator.ofFloat(invisibleCardView, "rotationY", -90, 0);
        invisToVis.setDuration(500);
        invisToVis.setInterpolator(mDecelerator);
        visToInvis.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                visibleCardView.setVisibility(View.INVISIBLE);
                invisToVis.start();
                invisibleCardView.setVisibility(View.VISIBLE);
            }
        });
        visToInvis.start();
    }
}
